package com.lianlianche.arch.jetpack.ktx

import android.net.ParseException
import com.google.gson.JsonIOException
import com.google.gson.JsonParseException
import org.json.JSONException
import retrofit2.HttpException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * <pre>
 *     @author : Mid
 *     e-mail  : boyce903301689@gmail.com
 *     time    : 2019/8/1
 *     desc    : 关于异常的扩展函数
 *     version : 1.0
 * </pre>
 */


/**
 * 将异常转换成提示信息
 */
fun Throwable.toMessage(): String {
    return when (this) {
        is UnknownHostException -> "网络不可用"
        is SocketTimeoutException -> "请求网络超时"
        is HttpException -> toCodeMessage()
        is JsonParseException, is ParseException, is JSONException, is JsonIOException -> "数据解析错误"
        else -> this.message ?: "未知错误"
    }
}


/**
 * 根据Http异常的状态码转换成提示信息
 */
fun HttpException.toCodeMessage(): String{
    return when (this.code()) {
        500 -> "服务器发生错误"
        404 -> "请求地址不存在"
        403 -> "请求被服务器拒绝"
        307 -> "请求被重定向到其他页面"
        else -> this.message()
    }
}